
var recorderManager = null;
import startRecord from 'dingtalk-jsapi/api/device/audio/startRecord';
import stopRecord from 'dingtalk-jsapi/api/device/audio/stopRecord';
import play from 'dingtalk-jsapi/api/device/audio/play';
import stop from 'dingtalk-jsapi/api/device/audio/stop';
import download from 'dingtalk-jsapi/api/device/audio/download';
import util from "/common/js/util.js";
import Qs from "qs";
/**
  {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46}
 */
const pageSize = 5;
var Timeout=null;
var Timeout2=null;
var time_obj={};
var item_timeout=null;
var app = getApp();
const base_residueTime=280;//297
const base_residueTimeLength="4:59";
var mediaData={};
Page({
  data: {
    scrollTop: 0,
    toView: "",
    btnStatus:"stop",
    payIng:false,//红灯闪烁
    recorderManager:null,
    recordAudioArr:[
      // {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46,"note":"这是我的学习笔记"
      // ,"createTime":"2024-07-10 09:44:25"},
      // {mediaId: "@lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA", remoteUrl: "https://static.dingtalk.com/media/lR_PD298BnsLiw0AALAg_JzMB9Hd2AZlUWoJ-uAA.ogg", duration: 2.46,"note":""
      // ,"createTime":"2024-07-10 09:44:25"}
    ],// 音频文件数组

    mediaData:null,
    startTime:0,
    timeLength:"00:00",//显示录制时长
    residueTime:base_residueTime,//倒计时 秒
    residueTimeLength:base_residueTimeLength,//剩余录制时间
    queryData:{},
    page: 1,
    pageSize: pageSize,
    showLoadMore: false,
    showLoadMoreTxt: "over",
    totalResult: pageSize,
    view:false,//查看模式
    loginUserId:"",//当前登录人员id
    dataList:{},
    enableNative:false
  },
  onLoad(e) {
    console.log("-进入");
   // console.log(e);
   let loginUserId=app.prototype.$userId;
    this.setData({
      queryData:e,
      loginUserId
    });
    let view=false;
    if(loginUserId==e.userId){
      view=false;
    }else{
      view=true;
    }
    this.setData({
      view,
      unSubmitArr:[]
    });
   
   dd.getSystemInfo({
    success: (res) => {
      // res.platform;
      console.log("--res.platform",res.platform);
      if(res.platform=="iOS"){
        this.setData({
          enableNative:true
        })
       }
    }
  })

  if(app.prototype.$userName=="刘庆峰"){
    this.setData({
      enableNative:true
    })
  }
   
  
    this.initFn();

    const updateManager = dd.getUpdateManager()

    updateManager.onCheckForUpdate(function (res) {
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function (ret) {
          //console.log(ret.version) // 更新版本号
          dd.confirm({
            title: '更新提示',
            content: '新版本已经准备好，是否重启应用？',
            success: function (res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                updateManager.applyUpdate()
              }
            }
          })
        })
      }
    })
 // this.showIntegralIcon();
  },
  onShow() {
  },
  getIsLogin(){
    let api = "/user/info/getIsLogin", list = {  };
    app.$post(api, list).then(re => {
      try {
        if (re.code == 401) {
          app.authLoginFn().then(res=>{
           // console.log("--detail--res:",res);
            this.tableList();

          })
        }
        else {
          this.tableList();
        };
      } catch (error) {
      }
    }).catch(err => {
     
    });
  },
  playFn(e){
    let arr = e.currentTarget.dataset.arr;
    let index= e.currentTarget.dataset.index;
    let id= e.currentTarget.dataset.id;
    let list= this.data[arr];
    let item=list[index];
   // console.log("--item:",item);
   let that=this;
   
    download({
      mediaId: id,
      success: (suc) => {
        console.log("--suc",suc);
        if(!item.play){
          play({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              // item.play=true;
              // item.startTime=0;
              let startTime=item.startTime;
              // item.duration2=item.duration;
              let duration=item.duration2;
              list.forEach(row=>{
                if(row.mediaId==id){
                  row.play=true;
                  row.startTime=0;
                  row.duration2=row.duration;
                  // let duration=row.duration2;
                }else{
                  row.play=false;
                  row.timeLength=that.format(row.duration);
                }
              })
              
              

              // item.timeLength="00:00";
              // console.log("list",list);
              that.setData({
                [`${arr}`]:list
              });


              // let time_id=setInterval(() => {
              //   startTime= startTime+1 ;
              //   let timeLength=that.format(startTime);
              //   item.timeLength=timeLength;
              //   duration=duration-1;
              //   item.duration2=duration;
              //   that.setData({
              //     [`${arr}`]:list
              //   });

              //   if(duration==0){
              //     clearInterval(time_id)
              //   }
                
              // }, 1000);
              // time_obj[id]=time_id;
              // console.log("--time_id",time_obj);


            },
            fail: (e) => {
              console.log("--错误",e);
            },
            complete: () => {},
          });
        }else{
          stop({
            localAudioId: suc.localAudioId,
            success: (ms) => {
              item.play=false;
              item.timeLength=that.format(item.duration);
              that.setData({
                [`${arr}`]:list
              })
              // let ti=time_obj[id];
              // console.log("--ti:",ti);
              // clearInterval(ti)
            },
            fail: (e) => {
              // console.log("--错误",e);
            },
            complete: () => {},
          })
        }
        

      },
      fail: () => {},
      complete: () => {},
    });
    
  },
  
  format(seconds) {//秒转化为分钟格式
    let s=Math.trunc(seconds);
    let minInt=Math.floor(s / 60);
    let min = minInt >= 10 ? minInt : '0' + minInt;
    s -= 60 * min;
    let sec = s >= 10 ? s : '0' + s;
    return  min + ':' + sec;
  },
  resetFn(){
    //重置参数
    this.setData({
      timeLength:"0:00",
      startTime:0,
      payIng:false,
      residueTimeLength:base_residueTimeLength,
      residueTime:base_residueTime
    })

  },

  initFn(){
    
    this.getIsLogin();
  //  this.showIntegralIcon2()
  },
  tableList(obj){
    let api = "/user/book/noteDetail";
    let list = {
      noteId: this.data.queryData.noteId,
    };
    // if(obj){
    //   list=util.mergeObj(list,obj)
    // }
    // console.log("--list:",list);
    let that = this;
    this.setData({
      showLoadMoreTxt: "load"
    });
    
   
    dd.showLoading({
        content: '数据加载中...',
      })
    app.$post(api, list).then(res => {
      dd.stopPullDownRefresh()
     dd.hideLoading();
      if (res.code == 200) {

        let dataList=res.data;
        dataList.timeLength= this.format(dataList.duration);
        
        this.setData({
          dataList,
          showLoadMoreTxt: "over"
        });
        dd.setNavigationBar({
          title: `《${dataList.bookName}》 P${dataList.startPage}-${dataList.endPage}`,
          success: () => {},
          fail: () => {},
          complete: () => {},
        });
        
      }else{
        util.message(res.message);

      }
    })
  },

  onPullDownRefresh() {
    // 页面被下拉
    this.setData({
      showLoadMoreTxt: "load"
    });
    this.searchFn();
  },
  searchFn(obj) {
    this.setData({
      page: 1,
      pageSize,
      recordAudioArr: []
    });
    this.tableList(obj)
  },
  onScrollToLower(){
   // console.log("---触底了!");
    this.tableList()
  },


  testGet(){
    dd.alert({
      title: '消息提示',
      content: JSON.stringify(mediaId),
      buttonText: '我知道了',
      success: () => {},
      fail: () => {},
      complete: () => {},
    });
  },


  bindKeyInput(e) {
    let key = "queryData.note";
    // util.debounce(() => {
     
    // }, 300);
    this.setData({
      [`${key}`]: e,
    });
  },

  onShareAppMessage() {

    let p = Qs.stringify(this.data.queryData);
    let path = '/pages/note/noteView/noteView';
     let url = `${path}?${p}`;
    return {
      title: '恒丽书城',
      desc: `${this.data.dataList.userName}的读书笔记`,
      path: url,
    };
  },
});
